from django.contrib.auth.models import Group
from rest_framework.permissions import BasePermission


class TeacherPermissions(BasePermission):
    """
    老师权限,只有老师才能对其操作
    """

    def has_permission(self, request, view):
        # 先拿到他(要登录的用户)
        user = request.user
        # 拿到老师组
        group = Group.objects.get(name='老师')
        # 拿到用户所在的组
        groups = user.groups.all()
        # 只有用户是超级管理员或者老师组在用户的组里面 则返回True
        return bool(user.is_superuser or group in groups)


class ActiveUserPermission(BasePermission):
    """
    当前登录用户只能操作当前的用户相关功能
    """

    def has_permission(self, request, view):
        user = request.user
        # 当前登录用户的id: user.id, 想要操作的用户的id: int(view.kwargs['pk'])
        return user.id == int(view.kwargs['pk'])


class MyBasePermission(BasePermission):
    def has_permission(self, request, view):
        if request.method in ['GET', 'HEAD', 'OPTION']:
            return True
            # 如果你是通过这样的请求方式过来的,那就返回True

        if request.user.is_superuser:
            return True
            # 如果你是超级用户,那就返回True

        if view.action == 'destroy':  # 如果是删除接口
            return request.user.is_superuser
        if view.action in ['create', 'update']:
            # if view.action == 'create' or view.action == 'update':  # 所有注册的接口都是用action
            user = request.user
            group = Group.objects.filter(name='老师')[0]  # filter拿到的是queryset,所以要用下标索引或first去取值
            groups = user.groups.all()  # 拿到用户所属的组,因为用户可能有多重身份
            return user.is_superuser or group in groups


# 装饰器 抽离公共部分
def auto_user(func):
    def f(self, request, *args, **kwargs):
        request.POST._mutable = True  # 让数据变成可变的
        request.data['user'] = str(request.user.id)  # 把创建题目的id改为本人的id
        return func(self, request, *args, **kwargs)
    return f
